package org.tinygame.herostory.cmdHandle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.tinygame.herostory.Broadcaster;
import org.tinygame.herostory.model.User;
import org.tinygame.herostory.model.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

/**
 * 用户攻击指令处理器
 */
public class UserAttkCmdHandler implements ICmdHandler<GameMsgProtocol.UserAttkCmd>{
    /**
     * 处理指令
     *
     * @param ctx
     * @param cmd
     *
     */
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserAttkCmd cmd) {
        if (null == ctx || null == cmd) {
            return;
        }
        //获取攻击者ID
        Integer attkUserId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if (null == attkUserId){
            return;
        }

        //获取被攻击者ID
        int targetUserId = cmd.getTargetUserId();

        //构建攻击结果消息体
        GameMsgProtocol.UserAttkResult.Builder resultBuilder = GameMsgProtocol.UserAttkResult.newBuilder();
        resultBuilder.setAttkUserId(attkUserId);
        resultBuilder.setTargetUserId(targetUserId);

        GameMsgProtocol.UserAttkResult newResult = resultBuilder.build();

        //广播给所有人，所有人都可以互相看到攻击的动作
        Broadcaster.broadcast(newResult);

        User targetUser = UserManager.getUserById(targetUserId);
        if (null == targetUser) {
            return;
        }

        int subtractHp = 10;
        targetUser.currHp = targetUser.currHp - subtractHp;

        //广播减血消息
        broadcastSubtractHp(targetUserId, subtractHp);
        if (targetUser.currHp <= 0) {
            //广播死亡消息
            broadcastDie(targetUserId);
        }
    }

    /**
     * 广播减血消息
     * @param targetUserId 目标用户Id
     * @param subtractHp 减血量
     */
    private static void broadcastSubtractHp(int targetUserId, int subtractHp){
        if (targetUserId <= 0 || subtractHp <= 0) {
            return;
        }
        //构建扣血结果消息体
        GameMsgProtocol.UserSubtractHpResult.Builder resultBuilder = GameMsgProtocol.UserSubtractHpResult.newBuilder();
        resultBuilder.setTargetUserId(targetUserId);
        resultBuilder.setSubtractHp(subtractHp);

        GameMsgProtocol.UserSubtractHpResult newResult = resultBuilder.build();

        //广播给所有人，所有人都可以互相看到攻击之后扣血的效果
        Broadcaster.broadcast(newResult);
    }

    /**
     * 广播死亡消息
     * @param targetUserId
     */
    private static void broadcastDie(int targetUserId) {
        GameMsgProtocol.UserDieResult.Builder resultBuilder = GameMsgProtocol.UserDieResult.newBuilder();
        resultBuilder.setTargetUserId(targetUserId);
        GameMsgProtocol.UserDieResult newResult = resultBuilder.build();

        Broadcaster.broadcast(newResult);
    }
}
